package com.masterclient.app.businessmodule.usermodule.login.contract;

import android.support.annotation.NonNull;

import com.eoner.baselib.container.CommonBaseResponse;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselibrary.utils.CookieNewUtil;
import com.eoner.baselibrary.utils.Utils;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.httpservice.RetrofitUtil2;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MultipartBody;

/**
 * Created by TMVPHelper on 2017/07/18
 */
public class LoginPresenter extends LoginContract.Presenter {

    @Override
    public void sendSms(String phone) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型

        builder.addFormDataPart("mobile",phone);
        builder.addFormDataPart("type","login");

        Observable<CommonBaseResponse> observable = RetrofitUtil2.getInstance().sendSms(builder.build().parts());
        Disposable disposable = toSubscribe(observable, (Consumer<CommonBaseResponse>) bean -> {
            if (bean != null && 0 == bean.getCode()) {
                mView.sendSmsSuccess();
            } else {
                mView.sendSmsFailed(bean.getMsg());
            }
        }, new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.sendSmsFailed("网络异常，请重试");
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void login(String phone,String code) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型

        builder.addFormDataPart("mobile",phone);
        builder.addFormDataPart("sms_code",code);
        builder.addFormDataPart("device_no", CookieNewUtil.getDevicedId());
        builder.addFormDataPart("platform","android");
        builder.addFormDataPart("app_version",CookieNewUtil.getVersionName(Utils.getContext()));

        Observable<CommonBaseResponse<LoginSuccessData>> observable = RetrofitUtil2.getInstance().login(builder.build().parts());
        Disposable disposable = toSubscribe(observable, (Consumer<CommonBaseResponse<LoginSuccessData>>) bean -> {
            if (bean != null && 0 == bean.getCode()) {
                mView.loginSuccess(bean.getData());
            } else {
                mView.loginFailed(bean.getMsg());
            }
        }, new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.loginFailed("网络异常，请重试");
            }
        });
        mRxManager.add(disposable);
    }
}